package com.spider.admin.utils;

import com.spider.admin.conf.CommandExecResult;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

public class OSCommandUtil {
    /**
     * @desc 执行cmd命令
     */
    public static CommandExecResult executeCmdForWin(String commandPath, String command, boolean wait,boolean readLine) {
        CommandExecResult commandExecResult = new CommandExecResult();
        try {

            Runtime runtime = Runtime.getRuntime();
            File dir = null;
            if (StringUtils.isNotEmpty(commandPath)) {
                dir = new File(commandPath);
            }
            Process process = runtime.exec("cmd /c " + command, null, dir);
            boolean execStatus = true;
            if (wait) {
                int exitCode = process.waitFor();
                if (exitCode != 0) {
                    execStatus = false;
                }
            }
            StringBuilder build = new StringBuilder();
            if(readLine){
                BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
                String line = null;

                while ((line = br.readLine()) != null) {
                    build.append("\n" + line);
                    commandExecResult.getResultLineMsg().add(line);
                    execStatus = true;
                }
                if (!execStatus) {
                    br = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
                    while ((line = br.readLine()) != null) {
                        build.append("\n" + line);
                        commandExecResult.getResultLineMsg().add(line);
                        execStatus = false;
                    }
                }
            }
            commandExecResult.setSuccess(execStatus).setResultMessage(build.toString()).setRunMessage("执行完成");
        } catch (Exception e) {
            commandExecResult.setSuccess(false).setRunMessage("执行异常：" + e.getMessage());
        }
        return commandExecResult;
    }


    /**
     * @desc 执行cmd命令
     */
    public static CommandExecResult executeCmdForLinux(String commandPath, String command, boolean wait,boolean readLine) {
        CommandExecResult commandExecResult = new CommandExecResult();
        try {
            Runtime runtime = Runtime.getRuntime();
            File dir = new File(commandPath);
            Process process = runtime.exec(command, null, dir);

            boolean execStatus = true;
            if (wait) {
                int exitCode = process.waitFor();
                if (exitCode != 0) {
                    execStatus = false;
                }
            }
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            String line = null;
            StringBuilder build = new StringBuilder();
            while ((line = br.readLine()) != null) {
                build.append("\n" + line);
                commandExecResult.getResultLineMsg().add(line);
                execStatus = true;
            }
            if (!execStatus) {
                br = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
                while ((line = br.readLine()) != null) {
                    build.append("\n" + line);
                    commandExecResult.getResultLineMsg().add(line);
                    execStatus = false;
                }
            }

            commandExecResult.setSuccess(execStatus).setResultMessage(build.toString()).setRunMessage("执行完成");
        } catch (Exception e) {
            commandExecResult.setSuccess(false).setRunMessage("执行异常：" + e.getMessage());
        }
        return commandExecResult;
    }

    /**
     * 当前系统是否Windows系统
     *
     * @return
     */
    public static boolean isWinOS() {
        String os = System.getProperty("os.name").toLowerCase();
        if (os != null && os.startsWith("windows")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断进程是否开启
     *
     * @param port
     * @return
     */
    public static boolean hasRunPort(int port) {
        boolean run = false;
        String command = "";
        if (isWinOS()) {
            command = "netstat -ano | findstr :" + port;
            CommandExecResult commandExecResult = executeCmdForWin(null, command, false,true);
            if (!commandExecResult.getResultLineMsg().isEmpty()) {
                for (String line : commandExecResult.getResultLineMsg()) {
                    run = line.contains("LISTENING");
                    if (run) break;
                }
            }
        } else {
            command = "netstat -tuln | grep :" + port;
            CommandExecResult commandExecResult = executeCmdForWin(null, command, false,true);
            run = commandExecResult.getResultLineMsg().size() > 0;
        }
        return run;
    }

    public static final CommandExecResult executeCmd(String commandPath, String command, boolean wait,boolean readLine) {
        if (isWinOS()) {
            return executeCmdForWin(commandPath, command, wait,readLine);
        } else {
            return executeCmdForLinux(commandPath, command, wait,readLine);
        }
    }

    public static final void main(String[] args) {
        boolean bol = hasRunPort(80);
        System.out.println(bol);
    }
}
